package inc.zhugastrov.sellerform;

import inc.zhugastrov.ui.AuthorizationForm;
import inc.zhugastrov.ui.UserUpdateForm;
import inc.zhugastrov.users.Account;
import inc.zhugastrov.users.Position;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static inc.zhugastrov.dbactions.DBActions.updateDBFromBasket;
import static inc.zhugastrov.dbactions.DBActions.saveOrder;
import static inc.zhugastrov.dbactions.DBActions.deleteItemFromBasket;
import static inc.zhugastrov.dbactions.DBActions.clearBasket;
import static inc.zhugastrov.ui.AuthorizationForm.getAuthorizedUser;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class BasketPanel extends JPanel implements ActionListener {
	private static Logger logger = Logger.getLogger(UserUpdateForm.class);
	private static BasketPanel instance;
	private JTable catalog;
	private ItemsTableModel model = new ItemsTableModel();
	private JScrollPane scrollPane;
	private JButton deleteFromBasket;
	private JButton orderButton;
	private Long someLong = 1111L;
	private JCheckBox isComplited;
	private Account authorizedUser = getAuthorizedUser();

	private BasketPanel() {
		DOMConfigurator.configure("prop.xml");
		init();
	}

	public static BasketPanel getInstance() {
		if (instance == null)
			instance = new BasketPanel();
		return instance;
	}

	public ItemsTableModel getModel() {
		return model;
	}

	public void addToBasket(Item item) {
		model.addRow(item);
	}

	private void init() {
		isComplited = new JCheckBox("Mark as complite");
		if (AuthorizationForm.getAuthorizedUser().getPosition() == Position.SELLER)
			add(isComplited);

		catalog = new JTable();
		catalog.setModel(model);
		catalog.getTableHeader().setReorderingAllowed(false);
		catalog.setFocusable(false);
		catalog.setSelectionMode(0);
		scrollPane = new JScrollPane(catalog);
		catalog.setPreferredScrollableViewportSize(new java.awt.Dimension(500,
				300));
		add(scrollPane);
		orderButton = new JButton("Create an order");
		orderButton.addActionListener(this);
		orderButton.setActionCommand("order");
		add(orderButton);
		deleteFromBasket = new JButton("Delete");
		deleteFromBasket.addActionListener(this);
		add(deleteFromBasket);

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (catalog.getRowCount() == 0) {
			JOptionPane.showMessageDialog(this,
					"Don't be silly - the basket is empty", "Bla bla bla",
					JOptionPane.WARNING_MESSAGE);
			return;
		}

		if (e.getActionCommand().equalsIgnoreCase("order")) {
			int n = JOptionPane.showConfirmDialog(this, "Are u sure?",
					"Create an order?", JOptionPane.YES_NO_OPTION);
			if (n == JOptionPane.YES_OPTION) {
				OrderIntr order = null;
				String items = "";
				Calendar cal = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
				if (!isComplited.isSelected()) {
					CurrentOrdersPane orderPane = CurrentOrdersPane.getInstance();
					order = new Order();
					order.setDate(sdf.format(cal.getTime()));
					List<OrderedItems> oi = new ArrayList<OrderedItems>();
					for (Product item : model.getData()) {
						oi.add(new OrderedItems((Item) item));
						items = items + "Item id = " + item.getId()
						+ " and amount = " + item.getAmountInStore()
						+ " " + "\n";
						
					}
					order.setItems(oi);
					someLong += 1L;
					order.setId(someLong);
					order.setSellerId(authorizedUser.getId().toString());
					order.setTotalPrice(model.getTotalPrice());
					saveOrder(order);
					orderPane.addOrder(order);

				}
				else{
					ComplOrderPane orderPane = ComplOrderPane.getInstance();
					order = new ComplOrder();
					order.setDate(sdf.format(cal.getTime()));
					List<OrderedItemsHistory> oi = new ArrayList<OrderedItemsHistory>();
					for (Product item : model.getData()) {
						oi.add(new OrderedItemsHistory((Item) item));
						items = items + "Item id = " + item.getId()
						+ " and amount = " + item.getAmountInStore()
						+ " " + "\n";
						
					}
					items = items + "and is mark as complited";
					order.setItems(oi);
					someLong += 1L;
					order.setId(someLong);
					order.setSellerId(authorizedUser.getId().toString());
					order.setTotalPrice(model.getTotalPrice());
					saveOrder(order);
					orderPane.addOrder(order);

				}
				logger.info("User "
						+ AuthorizationForm.getAuthorizedUser().getName()
						+ " create order with id " + order.getId() + "\n"
						+ " and items : " + "\n" + items);
				

				updateDBFromBasket(model.getData());
				clearBasket();
				model.emptyTable();
			}
		} else {
			if (catalog.getSelectedRow() == -1) {
				JOptionPane.showMessageDialog(this,
						"No orders selected, don't you see this?", "Error",
						JOptionPane.ERROR_MESSAGE);

				return;
			}
			int n = JOptionPane.showConfirmDialog(this,
					"Really whant to do this?", "Remove?",
					JOptionPane.YES_NO_OPTION);
			if (n == JOptionPane.YES_OPTION) {
				MainPanel mainPanel = MainPanel.getInstance();
				Item item = (Item) model.getRow(catalog.getSelectedRow());
				Long id = item.getId();
				deleteItemFromBasket(id);
				Item itemToChange = new Item();
				if ((itemToChange = (Item) mainPanel.getModel().findWithId(id)) != null)
					mainPanel.getModel().changeAmount(item.getAmountInStore(),
							itemToChange);
				model.deleteRow(catalog.getSelectedRow());
			}
		}
	}
}
